<template>
  <!-- 新建问候 -->
  <Top-Page class="new-greeting-box">
    <Friend-selection
      v-show="friendSelectionShow"
      :checkUsersList="checkUsersList"
      :checkLabelObj="checkLabelObj"
      v-model:contacts="contacts"
      v-model:friendSelectionShow="friendSelectionShow"
      v-model:importType="importType"
    />
    <!-- 从XX选择好友 -->
    <Gather-import
      v-if="importType"
      :checkUsersList="checkUsersList"
      v-model:contacts="contacts"
      v-model:friendSelectionShow="friendSelectionShow"
      v-model:importType="importType"
      v-model:checkLabelObj="checkLabelObj"
    />
  </Top-Page>
</template>

<script>
import FriendSelection from './src/friend-selection/friend-selection';
import GatherImport from './src/gather-import/gather-import';
export default {
  data() {
    return {
      friendSelectionShow: true,
      contacts: [],
      checkLabelObj: {
        group: [],
        label: [],
        sex: [],
        age: []
      },
      importType: ''
    };
  },
  components: { FriendSelection, GatherImport },
  created() {
    this.disposeContacts();
  },
  watch: {
    contacts: {
      handler(newArr) {
        newArr.forEach((parent) => {
          const allSearchFalse = parent.children.every((child) => child.search === false);
          parent.searchShow = !allSearchFalse;
        });
      },
      deep: true
    }
  },
  computed: {
    checkUsersList() {
      let arr = [];
      this.contacts.forEach((item) => {
        if (item.children) {
          item.children.forEach((it) => {
            console.log(it, 'itwww');
            it.checked && arr.push(it);
          });
        }
      });
      return arr;
    }
  },
  methods: {
    //处理联系人
    disposeContacts() {
      //联系人
      const allContacts = uni.getStorageSync('allContacts');

      const contacts = allContacts.filter((item) => {
        return item.is_group == 0;
      });

      // 将联系人进行排序
      const sorted = contacts.sort((a, b) => {
        if (a.index === '#') {
          return 1;
        }
        if (b.index === '#') {
          return -1;
        }

        return a.index.localeCompare(b.index, 'zh');
      });

      // 重组联系人
      const result = sorted.reduce((acc, cur) => {
        //自定义状态
        cur['search'] = false; //搜索
        cur['checked'] = false; //选中
        const index = cur.index;
        const existingIndex = acc.findIndex((item) => item.name === index);
        if (existingIndex === -1) {
          acc.push({ name: index, searchShow: true, children: [cur] });
        } else {
          acc[existingIndex].children.push(cur);
        }
        return acc;
      }, []);

      this.contacts.push(...result);
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
